package controllers

import (
	"backend/common"
	"backend/models"
	"context"
	"errors"
	"fmt"

	"encoding/json"

	"github.com/jinzhu/gorm"
)

// 创建用户意图记录
func createUserIntention(userID uint, intentionMsg models.Intention) (*models.UserIntention, error) {
	// 将 IntentionMessage 转换为 JSON 字符串存储
	request, err := json.MarshalIndent(intentionMsg, "", "  ")
	if err != nil {
		return nil, err
	}

	userIntention := &models.UserIntention{
		UserID:    userID,
		Intention: intentionMsg.Intention,
		Request:   string(request),
	}

	// 保存到数据库
	result := common.DB.Create(userIntention)
	if result.Error != nil {
		return nil, result.Error
	}

	return userIntention, nil
}

func getUserIntention(intentionID uint) (*models.UserIntention, error) {
	userIntention := &models.UserIntention{}

	result := common.DB.First(userIntention, intentionID)
	if result.Error != nil {
		return nil, result.Error
	}
	return userIntention, nil
}

func updateUserIntention(intention *models.UserIntention) error {
	userIntention := &models.UserIntention{}
	result := common.DB.First(userIntention, intention.ID)
	if result.Error != nil {
		return result.Error
	}
	if userIntention.UserID != intention.UserID {
		return fmt.Errorf("没有权限更新")
	}

	result = common.DB.Save(intention)

	return result.Error
}

func deleteUserIntention(userID uint, intentionID uint) error {
	userIntention := &models.UserIntention{}
	result := common.DB.First(userIntention, intentionID)
	if result.Error != nil {
		return result.Error
	}

	if userIntention.UserID != userID {
		return fmt.Errorf("没有权限更新")
	}

	result = common.DB.Delete(userIntention)

	return nil
}

// 创建工作流记录
func createDataflow(userID uint, intentionID uint, workflow models.Workflow) (*models.Dataflow, error) {
	request, err := json.MarshalIndent(workflow, "", "  ")
	if err != nil {
		return nil, err
	}

	dataflow := &models.Dataflow{
		UserID:      userID,
		IntentionID: intentionID,
		Dataflow:    string(request),
	}

	// 先尝试查找现有记录
	existing := &models.Dataflow{}
	err = common.DB.Where("intention_id = ?", intentionID).First(existing).Error

	if err == nil {
		// 存在则更新
		existing.Dataflow = string(request)
		existing.UserID = userID
		err = common.DB.Save(existing).Error
		if err != nil {
			return nil, fmt.Errorf("failed to update dataflow: %v", err)
		}
		return existing, nil
	} else if errors.Is(err, gorm.ErrRecordNotFound) {
		// 不存在则创建
		err = common.DB.Create(dataflow).Error
		if err != nil {
			return nil, fmt.Errorf("failed to create dataflow: %v", err)
		}
		return dataflow, nil
	} else {
		// 其他数据库错误
		return nil, fmt.Errorf("database error: %v", err)
	}
}

func updateDataflow(newDataflow *models.Dataflow, userID uint) error {
	dataflow := &models.Dataflow{}
	result := common.DB.First(dataflow, newDataflow.ID)
	if result.Error != nil {
		return result.Error
	}

	if userID != dataflow.UserID {
		return fmt.Errorf("没有权限更新")
	}

	newDataflow.IntentionID = dataflow.IntentionID

	result = common.DB.Save(newDataflow)

	return result.Error
}

func getDataflow(dataflowID uint) (*models.Dataflow, error) {
	userDataflow := &models.Dataflow{}

	result := common.DB.First(userDataflow, dataflowID)
	if result.Error != nil {
		return nil, result.Error
	}
	return userDataflow, nil
}

func getDataflowByIntention(intentionID uint) (*models.Dataflow, error) {
	dataflow := &models.Dataflow{}

	result := common.DB.Where("intention_id = ?", intentionID).First(dataflow)
	if result.Error != nil {
		return nil, result.Error
	}

	return dataflow, nil
}

func getUserHistory(userID uint) (*models.History, error) {
	if err := common.DB.Select("id").Where("id = ?", userID).First(&models.User{}).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, fmt.Errorf("用户不存在")
		}
		return nil, fmt.Errorf("查询用户失败: %w", err)
	}

	history := &models.History{UserID: userID}

	var hItems []models.HistoryItem

	common.DB.Model(&models.UserIntention{}).Select("user_intentions.id AS intention_id, dataflows.id AS dataflow_id,"+
		"user_intentions.intention,user_intentions.created_at,user_intentions.updated_at").Joins("left join "+
		"dataflows on dataflows.intention_id = user_intentions.id").Where("user_intentions.user_id = ?", userID).Scan(&hItems)

	history.Items = hItems

	return history, nil
}

var ctx = context.Background()

func insertFileID(userID uint, fileID string) error {
	key := fmt.Sprintf("%d", userID) // 直接格式化为字符串
	_, err := common.RedisClient.SAdd(ctx, key, fileID).Result()
	if err != nil {
		return fmt.Errorf("redis插入失败: %v", err)
	}

	return nil
}

func checkFileID(userID uint, fileID string) (bool, error) {
	key := fmt.Sprintf("%d", userID)
	// 使用 SIsMember 检查 fileID 是否在集合中
	ans, err := common.RedisClient.SIsMember(ctx, key, fileID).Result()
	if err != nil {
		return false, fmt.Errorf("代码文件查询失败: %v", err)
	}

	return ans, nil
}

func clearSet(userID uint) error {
	key := fmt.Sprintf("%d", userID)
	_, err := common.RedisClient.Del(ctx, key).Result()
	if err != nil {
		return fmt.Errorf("redis删除失败: %v", err)
	}

	return nil
}
